package cn.fzkj.security.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class MySecurityConf extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 定制请求的授权规则
        http.authorizeRequests().antMatchers("/","/login").permitAll()
                .antMatchers("/user/**").hasRole("ADMIN")
                .antMatchers("/book/**").hasRole("MANAGER");

        // 开启自动配置的登录功能
        // .loginProcessingUrl("http://www.baidu.com") : 指定登录请求处理的url
        http.formLogin();

        // 1. /login处理登录请求
        // 2. /login?error 表示登录失败

        // 开启注销功能
        http.logout().logoutSuccessUrl("/");
        /**
         * 1.访问 /logout，用户退出，清空session
         */
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("ymm")
                .password(new BCryptPasswordEncoder().encode("23")).roles("ADMIN")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("mr")
                .password(new BCryptPasswordEncoder().encode("27")).roles("MANAGER")
                .and()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("lj")
                .password(new BCryptPasswordEncoder().encode("22")).roles("common");
    }
}
